import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';
import { login } from '@/services';
import { InLogin } from '@/types';
import Cookies from 'js-cookie';
export interface LoginModelState {
  Logincode: Partial<InLogin>;
}

export interface LoginModelType {
  namespace: 'login';
  state: LoginModelState;
  effects: {
    query: Effect;
    login: Effect;
  };
  reducers: {
    save: Reducer<LoginModelState>;
  };
  subscriptions: { setup: Subscription };
}

const LoginModel: LoginModelType = {
  namespace: 'login',

  state: {
    Logincode: {},
  },

  effects: {
    *query({ payload }, { call, put }) { },
    *login({ payload }, { call, put }) {
      let result = yield call(login, payload);
      if (result) {
        Cookies.set('Authorization', `bearer${result.access_token}`, {
          expires: 7,
          path: '/',
        });
        location.href = "/home"
      }
    },
  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    // 启用 immer 之后
    // save(state, action) {
    //   state.name = action.payload;
    // },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/') {
          dispatch({
            type: 'query',
          });
        }
      });
    },
  },
};

export default LoginModel;
